3#!/usr/bin/python

import socket
import threading

class TCPServer:
	"""Base class for various socket-based server class"""
	
	address_family = socket.AF_INET
	socket_type = socket.SOCK_STREAM
	request_queue_size = 1024           # The max waiting connect queue
	allow_reuse_address = 0             # Could we reuse the address?

	
	def __init__(self, ip, port):
		"""Constructor."""
		self.socket = socket.socket(self.address_family, self.socket_type)
		if self.allow_reuse_address:
			self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.socket.bind((ip, port))
		self.socket.listen(self.request_queue_size)


	def close(self):
		"""Called to clean-up the server."""
		self.socket.close()


	def fileno(self):
		"""Return socket file number, For select or poll."""
		return self.socket.fileno()


	def get_request(self):
		"""Get the request and client address from the socket."""
		return self.socket.accept()


	def close_request(self, request):
		"""Called to clean up an individual request."""
		request.close()



class BaseServer:
	"""Base threading server"""
	
	daemon_threads = 1  #dispatch thread 
	
	def __init__(self, ip, port):
		"""Init socket and count_lock"""
		self.socket = TCPServer(ip, port)            # Unix socket
		
	def start(self, event):
		"""Main loop, listening on given port
		Each thread of one connection, 
		"""
		request, addr = self.socket.get_request()
		t = threading.Thread(target = event.handler,
				     args = (request, addr))
		if self.daemon_threads:
			t.setDaemon(1)
		t.start()
		
	def stop(self):
		self.socket.close()


class Event:
	def __init__(self):
		pass
	
	def handler(self, request, address):
		pass



if __name__ == '__main__':
	test = BaseServer('127.0.0.1', 20005)
	event = Event()
	while True:
		test.start(event)		
	
